package org.clob4eclipse.popup.actions;

import java.io.IOException;
import java.io.InputStream;


import org.clob4eclipse.Activator;
import org.clob4eclipse.Config;
import org.clob4eclipse.PluginData;
import org.clob4eclipse.PluginLogger;
import org.eclipse.core.resources.IFile;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

public class SaveOracleClob implements IObjectActionDelegate {

	private Shell shell;
	private IFile activeFile = null;
	
	/**
	 * Constructor for SaveOracleClob.
	 */
	public SaveOracleClob() {
		super();
	}

	/**
	 * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
	 */
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		shell = targetPart.getSite().getShell();
	}
	
	/**
	 * @see IActionDelegate#run(IAction)
	 */
	public void run(IAction action) {
		
		Config config = null;
		InputStream stream = null;
		
		if (activeFile != null) {
			PluginData data = Activator.getPluginData();
			try {
				config = new Config(data);
				stream = activeFile.getContents();
				
				String fileName = activeFile.getName().substring(0, activeFile.getName().length()-5);
				
				PluginLogger.logInfo("file name="+activeFile.getName());
				PluginLogger.logInfo("file name sub="+activeFile.getName().substring(0, activeFile.getName().length()-5));

				config.commitClobFile(stream, fileName, shell);
				
			} catch (Exception e) {
				PluginLogger.logError("error saving clob", e);
				MessageDialog.openInformation(
						shell,
						"OracleClobEditor Plug-in",
						"FAILED: Save '"+activeFile.getName()+"'!");
				return;
			} finally {
				try {
					if (stream != null)	stream.close();
				} catch (IOException e1) {
				}				
			}		
		}
	}

	/**
	 * @see IActionDelegate#selectionChanged(IAction, ISelection)
	 */
	public void selectionChanged(IAction action, ISelection selection) {
		if (selection instanceof IStructuredSelection) {
	 		 IStructuredSelection structuredSelection = (IStructuredSelection) selection;
	  		    activeFile = (IFile)structuredSelection.getFirstElement();
	  		}
	}
}
